<template>
  <el-dialog
    v-model="show"
    title="关联项目列表"
    width="60vw"
    destroy-on-close
    center
    custom-class="add-check"
    @close="handleCancel"
  >
    <div class="check-table">
      <div class="form-left">
        <el-button type="primary" class="add-option" @click="handleDetail(1)"
          >新增</el-button
        >
        <p>
          项目剩余预算（万元）：<span
            class="remain"
            :class="Number(relationInfo.remainAmount) < 0 ? 'text-danger' : ''"
            >{{ relationInfo.remainAmount }}</span
          >
        </p>
      </div>
      <el-table
        :data="tableData"
        stripe
        v-loading="loading"
        :header-cell-style="{
          background: '#F7F9FD',
          color: '#000',
          height: '48px',
          borderTop: '1px soild #E4E8F2'
        }"
      >
        <el-table-column type="index" label="序号" width="80">
          <template v-slot="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="jcProjectName" label="项目名称">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              placement="bottom-end"
              popper-class="tooltip-popper"
            >
              <template #content>
                <div style="max-width: 150px; line-height: 18px">
                  {{ row.projectName }}
                </div>
              </template>
              <span class="pro-text" @click="toProBudget(row)">{{
                row.projectName
              }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="projectTypeName" label="项目类型">
        </el-table-column>
        <el-table-column prop="sectionName" label="标段"> </el-table-column>
        <el-table-column prop="budgetAmount" label="使用预算金额（万）">
        </el-table-column>
        <el-table-column prop="contractAmount" label="合同金额(万)">
          <template #default="{ row }">
            <span
              :class="
                Number(row.contractAmount) > Number(row.budgetAmount)
                  ? 'text-danger'
                  : ''
              "
              >{{ row.contractAmount }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="rate" label="费率(%)"> </el-table-column>
        <el-table-column prop="leaderName" label="项目管理员">
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              @click="handleDetail(2, row)"
              v-auth="`/projects/purchase--edit`"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              class="btns-danger"
              @click="showDeleteMessageBox(row)"
              v-auth="`/projectsS/purchase--delete`"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <re-pagination
        v-if="total > 0"
        :total="total"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleChangePage"
      />
    </div>

    <relation-detail
      v-if="detailData.dialogFormVisible"
      :detailData="detailData"
      :jcProjectInfo="jcProjectInfo"
      @emitClose="detailData.dialogFormVisible = false"
      @updateClose="updateClose"
      :totalAmount="totalAmount"
      :remainAmount="relationInfo.remainAmount"
    />
  </el-dialog>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { budgetList, delProjectBudget } from "/@/api/purchase";
import RePagination from "/@/components/RePagination/index.vue";
import relationDetail from "./relationDetail.vue";
import { ElMessageBox } from "element-plus";
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
export default defineComponent({
  name: "purchaseRelation",
  components: { relationDetail, RePagination },
  props: {
    relationInfo: {
      type: Object,
      default: () => {}
    }
  },
  emits: ["handleCancel", "updateClose"],
  setup(props, { emit }) {
    const loading = ref<boolean>(false);
    const router = useRouter();
    const show = ref<boolean>(true);
    const jcProjectInfo = {
      jcProjectId: props.relationInfo.id,
      jcProjectName: props.relationInfo.jcProjectName
    };
    const formInline = reactive({
      ext1: "1",
      budgetNameLike: "",
      budgetTypeCode: "",
      jcProjectId: props.relationInfo?.id,
      pageNum: 1,
      pageSize: 10
    });
    const totalAmount = ref<number>(0); //已使用的预算
    const tableData = ref([]);
    const total = ref<number>(0);
    const detailData = reactive({
      title: "新增关联项目",
      type: 1,
      id: "",
      dialogFormVisible: false
    });

    //获取数据列表
    const getTableList = async (obj: object = {}) => {
      try {
        loading.value = true;
        const { code, data } = await budgetList({
          ...obj
        });
        if (code === 200) {
          tableData.value = data.list;
          total.value = data.rows;
          totalAmount.value = 0;
          if (tableData.value?.length) {
            tableData.value.forEach(item => {
              totalAmount.value += Number(item.budgetAmount);
            });
          }
          console.log(totalAmount.value, "totalAmount.valuetotalAmount.value");
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    };

    const handleCancel = async () => {
      emit("handleCancel");
    };

    //新增编辑集采关联项目
    const handleDetail = async (type, row) => {
      if (type === 1) {
        if (props.relationInfo.remainAmount < 0) {
          ElMessageBox.confirm("项目预算已经超支，确定新增关联项目", "", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            iconClass: "el-icon-warning"
          })
            .then(() => {
              detailData.title = "新增关联项目";
              detailData.type = 1;
              detailData.id = "";
              detailData.dialogFormVisible = true;
            })
            .catch(() => {});
        } else {
          detailData.title = "新增关联项目";
          detailData.type = 1;
          detailData.id = "";
          detailData.dialogFormVisible = true;
        }
      } else {
        detailData.title = "编辑关联项目";
        detailData.type = 2;
        detailData.id = row.id;
        detailData.dialogFormVisible = true;
      }
    };

    const showDeleteMessageBox = row => {
      ElMessageBox.confirm("确定删除该条记录吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        iconClass: "el-icon-warning"
      })
        .then(() => {
          handleDelete(row);
        })
        .catch(() => {});
    };

    //删除关联项目
    const handleDelete = async row => {
      try {
        const { code, message } = await delProjectBudget({ id: row.id });
        if (code === 200) {
          NotifMessage.success(message);
          emit("updateClose");
          getTableList(formInline);
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const toProBudget = async row => {
      ["A"].includes(row.projectTypeCode)
        ? router.push(`/projects${row.projectTypeCode}/proManage/budget`)
        : router.push(`/projectsB`);
      storageLocal.setItem("projectInfo", {
        id: row.projectId,
        name: row.projectName,
        typeCode: row.projectTypeCode,
        typeName: row.projectTypeName,
        leaderId: row.leaderId,
        leaderName: row.leaderName
      });
    };

    const updateClose = async () => {
      emit("updateClose");
      getTableList(formInline);
      detailData.dialogFormVisible = false;
    };

    const handleChangePage = () => {
      getTableList(formInline);
    };

    getTableList(formInline);
    return {
      show,
      handleCancel,
      loading,
      tableData,
      total,
      detailData,
      handleDetail,
      jcProjectInfo,
      updateClose,
      showDeleteMessageBox,
      toProBudget,
      handleChangePage,
      formInline
    };
  }
});
</script>
<style lang="scss" scoped>
:deep .add-check {
  .el-dialog__body {
    padding: 20px 40px 8px 10px;
  }
}
.check-table {
  padding: 20px;
  .card-header {
    font-weight: bold;
    color: #494c53;
  }
  .el-table {
    width: 100%;
    margin: 20px 0;
    margin-bottom: 40px;
  }
  .form-left {
    display: flex;
    align-items: center;
    p {
      font-size: 14px;
      margin-left: 10px;
      font-weight: 400;
      color: #494c53;
    }
  }
  .remain {
    font-size: 20px;
    font-weight: 600;
    color: #494c53;
  }
  .text-danger {
    color: #e45d5d;
  }
}
.pro-text {
  color: #5298ff;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
